package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClazzNotAllowedDeleteException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.domain.Clazz;
import com.itheima.pojo.domain.Emp;
import com.itheima.pojo.domain.Student;
import com.itheima.pojo.vo.PageResult;
import com.itheima.pojo.dto.ClazzPageQueryDTO;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void addClazzInfo(Clazz clazz) {
        LocalDateTime now = LocalDateTime.now();
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);

        clazzMapper.addClazzInfo(clazz);
    }

    /**
     * 分页查询
     * @param clazzPageQueryDTO
     * @return
     */
    @Override
    public PageResult list(ClazzPageQueryDTO clazzPageQueryDTO) {
        //开始分页
        PageHelper.startPage(clazzPageQueryDTO.getPage(), clazzPageQueryDTO.getPageSize());
        //查询分页数据
        Page<Clazz> clazzsList = clazzMapper.sleInfoByPage(clazzPageQueryDTO);
        clazzsList.getResult().stream().forEach(c->c.panDuan());
        PageResult<Clazz> result = new PageResult<>(clazzsList.getTotal(), clazzsList.getResult());
        return result ;
    }

    @Override
    public void update(Clazz clazz) {

        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> listAll() {

        List<Clazz> clazzes = clazzMapper.listAll();

        return clazzes;
    }

    @Override
    public Clazz getClazzInfoById(Integer id) {

        Clazz clazz = clazzMapper.getClazzInfoById(id);
        return clazz;
    }

    @Override
    public void deleteClazz(Integer id) {
        //传入参数为clazz表的id
        //根据clazz的id 查询班级是否有学生
        List<Student> listByClazzId = studentMapper.listStudentByClazzId(id);

        if (!listByClazzId.isEmpty()){
            throw new ClazzNotAllowedDeleteException("班级任然存在学生无法删除");
        }
        clazzMapper.deleteClazz(id);
        log.info("删除成功");
    }
}
